package com.luck.easyfoodbatch.ui;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.CouponAdapter;
import com.luck.easyfoodbatch.mvp.mine.ChangeVouchersModel;
import com.luck.easyfoodbatch.mvp.mine.ChangeVouchersPresenter;
import com.luck.easyfoodbatch.mvp.mine.ChangeVouchersView;
import com.luck.easyfoodbatch.mvp.mine.PointChangeModel;
import com.luck.easyfoodbatch.mvp.mine.PointChangePresenter;
import com.luck.easyfoodbatch.mvp.mine.PointChangeView;
import com.luck.easyfoodbatch.mvp.model.ChangeVouchers;
import com.luck.easyfoodbatch.mvp.model.PointModel;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyrecyclerview.EasyRecyclerView;
import com.luck.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//积分兑换界面
public class ExchangeActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnLoadMoreListener, PointChangeView, ChangeVouchersView {

    @BindView(R.id.tv_my_score)
    TextView tvMyScore;
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.btn_yes)
    Button btnYes;
    private CouponAdapter adapter;
    private List<PointModel.DataBean.ModelsBean> list = new ArrayList<>();
    private PointChangeModel changeModel;
    private int totalPage = 1;
    private int page = 1;
    private int isRefresh = 0;// 0普通请求，1下拉刷新，2上拉加载
    private int sumScore = 0;
    private ChangeVouchersModel vouchersModel;
    private String vids = "";
    private String vidss = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exchange, "积分兑换", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        if (user != null) {
            tvMyScore.setText(user.getPoint() + "");
        }
        vidss = getIntent().getStringExtra("vids");
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(manager);
        adapter = new CouponAdapter(mContext);
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                PointModel.DataBean.ModelsBean bean = list.get(position);
                String point = bean.getNeed_point();
                int need_point = 0;
                if (!Tools.isNull(point)) {
                    need_point = Integer.parseInt(point);
                }
                if (bean.isChecked()) {
                    bean.setChecked(false);
                    sumScore -= need_point;
                } else {
                    bean.setChecked(true);
                    sumScore += need_point;
                }
                adapter.notifyDataSetChanged();
                tvScore.setText(sumScore + "分");
            }
        });
        showProgressDialog(getString(R.string.app_loading));
        changeModel = new PointChangePresenter(this, mContext);
        changeModel.getPointChangeList(page, vidss);
        adapter.addAll(list);
        recyclerView.setAdapter(adapter);
        recyclerView.setRefreshListener(this);
    }

    @OnClick(R.id.btn_yes)
    public void onClick() {
        if (user != null) {
            int point = user.getPoint();
            if (point == 0) {
                T.showToast(mContext, "积分不足，不能兑换");
                return;
            }
        }

        StringBuffer sb = new StringBuffer();
        for (PointModel.DataBean.ModelsBean item : list) {
            if (item.isChecked()) {
                sb.append(item.getVid()).append(",");
            }
        }
        vids = sb.toString();
        if (!Tools.isNull(vids)) {
            if (sb.toString().endsWith(",")) {
                vids = vids.substring(0, vids.toString().length() - 1);
            }
        }

        if (Tools.isNull(vids)) {
            T.showToast(mContext, "请选择兑换优惠券");
            return;
        }
        vouchersModel = new ChangeVouchersPresenter(this, mContext);
        vouchersModel.changeVouchers(vids);
    }

    @Override
    public void onLoadMore() {
        //刷新
        isRefresh = 1;
        page++;
        if (!isNetworkConnected()) {
            adapter.pauseMore();
            return;
        }
        if (page > totalPage) {
            adapter.stopMore();
            return;
        }
        changeModel.getPointChangeList(page, vidss);
    }

    @Override
    public void onRefresh() {
        isRefresh = 0;
        page = 1;
        changeModel.getPointChangeList(page, vidss);
    }


    @Override
    public void pointChangeSuccess(PointModel model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            totalPage = model.getData().getTotalPage();
            // 下拉刷新 清空集合
            switch (isRefresh) {
                case 0:
                    list.clear();
                    list = model.getData().getModels();
                    break;
                case 1:
                    // 下拉刷新
                    list.addAll(model.getData().getModels());
                    break;
            }
            adapter.clear();
            adapter.addAll(list);
            adapter.notifyDataSetChanged();
        } else {
            T.showToast(mContext, model.getMsg());
        }
    }

    @Override
    public void httpStatusError() {
        T.showToast(mContext, getResources().getString(R.string.app_http_error));
    }


    @Override
    public void changeVouchersSuccess(ChangeVouchers model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            T.showToast(mContext, model.getMsg());
            if (user != null) {
                for (PointModel.DataBean.ModelsBean item : list) {
                    item.setChecked(false);
                }
                adapter.notifyDataSetChanged();
                tvScore.setText("0分");
                int point = user.getPoint();
                // 原有积分减去，兑换积分
                int sum = point - sumScore;
                user.setPoint(sum);
                tvMyScore.setText(user.getPoint() + "");
                App.getInstance().saveObject(user, HttpUtil.USER_KEY);
                setResult(RESULT_OK);
                finish();
            }
        } else {
            T.showToast(mContext, model.getMsg());
        }
    }


    @Override
    public void hideLoading() {
        hideShowProgress();
    }
}
